const app = getApp();
const { fetch } = require('../../utils/util.js')
Page({
  data: {
    markers: [],
    slides: [],
    cases: [], // 案列推荐
    designs: [], // 设计机构
    pageIndex: 0,
    pageSize: 4,
    totalCount: 0,
    hasMore: true,
    params: {},
  },

  onLoad: function (options) {
    const _this = this;
    // banner
    fetch({
      url: 'api/zhuang/GetBannerList',
      params: {},
      success: (res) => {
        if (res instanceof Array) {
          _this.setData({
            slides: res
          })
        }
      }
    })

    // 地图
    fetch({
      url: 'api/zhuang/GetmarkersList',
      params: { lv: 1 },
      success: (res) => {
        console.log('地图:')
        console.log(res)
        if (res instanceof Array) {
          let markers = [];
          for (let i = 0; i < res.length; i++) {
            let marker = _this.createMarker(res[i]);
            markers.push(marker)
          }
          _this.setData({
            markers: markers
          })
        }
      }
    });

    // 案列推荐
    fetch({
      url: 'api/zhuang/GetGonDiList',
      params: {
        rows: 2
      },
      success: (res) => {
        console.log('案列推荐:')
        console.log(res)
        if (res && res.items) {
          _this.setData({
            cases: res.items
          })
        }
      }
    })

    this.loadmore()    
  },

  onPullDownRefresh: function () {
    this.setData({ pageIndex: 0, hasMore: true, params: {} }, () => {
      wx.stopPullDownRefresh()
    })
  },

  /**
  * 页面上拉触底事件的处理函数--加载数据
  */
  onReachBottom: function () {
    this.loadmore()
  },

  // 加载更多
  loadmore: function () {
    const _this = this;
    if (!this.data.hasMore) return;
    let { pageIndex, pageSize, params, designs } = this.data;
    const obj = { ...params, page: ++pageIndex, rows: pageSize }

    fetch({
      url: 'api/zhuang/GetSiteList',
      params: obj,
      success: (res) => {
        console.log('设计机构:')
        console.log(res)
        if (res && res.items) {
          const totalCount = parseInt(res.totalItems)
          const hasMore = pageIndex * pageSize < totalCount
          let tempList = null;
          if (pageIndex == 1) {
            tempList = res.items
          } else {
            tempList = designs.concat(res.items)
          }
          console.log(tempList)
          this.setData({ totalCount, pageIndex, hasMore, designs: tempList })
        }
      }
    });
  },

  // 创建marker对象
  createMarker(item) {
    let marker = {
      ...item,
      id: item.aid || 0,
      iconPath: "../../assets/icons/dp-gl.png"
    };
    return marker;
  },

  // 点击marker 
  markertap: function (e) {
    app.pageTo(`/pages/mapContent/mapContent?id=${e.markerId}`)
  },

  tabpage: function (e) {
    app.redirectTo(e.currentTarget.dataset.url)
  },

  pageTo: function (e) {
    app.pageTo(e.currentTarget.dataset.url)
  },

})